package com.string.actortv.activity.bde4;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.string.actortv.R;
import com.string.actortv.dto.MovieList;
import com.string.actortv.enums.PlayerType;
import com.string.actortv.util.Bde4Util;
import com.string.actortv.util.MyHttpUtil;
import com.string.actortv.util.SQLiteHelper;
import com.string.actortv.util.UIHelper;

import java.util.ArrayList;
import java.util.HashMap;

public class Bde4Activity extends Activity {

    private static String searchStr = "";
    private Context mContext;
    private SimpleAdapter gridAdapter;
    private GridView gridView;
    private View selectedView;
    private ArrayList<HashMap<String, Object>> items;
    private int currentPage = 1;
    private EditText mUrl;
    private boolean hasNext = true;
    private String type = "all";
    private int retryTimes = 0;
    private SQLiteHelper sqLiteHelper;

    private final Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                default:
                    if (gridAdapter != null) {
                        gridAdapter.notifyDataSetChanged();
                    }
            }
            return true;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        if (getIntent().getStringExtra("type") != null) {
            type = getIntent().getStringExtra("type");
        }
        if ("all".equals(type)) {
            setContentView(R.layout.activity_main_list);
            initBtnListener();
        } else {
            setContentView(R.layout.activity_main_season_list);
        }
        sqLiteHelper = new SQLiteHelper(mContext);

        newInit();
    }

    private void loadSpareItems(int pageNo, boolean clearFlag) {
        if (clearFlag) {
            items.clear();
        }
        currentPage = pageNo + 1;
        UIHelper.showDialogForLoading(mContext, "正在加载...");
        Bde4Util.getMovieListAsync(pageNo, searchStr, type, tempList -> {
            if (tempList == null) {
                retryTimes++;
                if (retryTimes < MyHttpUtil.RETRY_TIMES) {
                    Log.d("list-retry", "Bde4Activity重新尝试连接");
                    loadSpareItems(pageNo, clearFlag);
                } else {
                    retryTimes = 0;
                    UIHelper.dismiss();
                }
                return;
            }
            retryTimes = 0;
            if (tempList.isEmpty()) {
                hasNext = false;
                UIHelper.dismiss();
                return;
            }
            HashMap<String, Object> item;
            for (MovieList movieList : tempList) {
                item = new HashMap<>();
                item.put("title", movieList.getName());
                item.put("icon", movieList.getImgUrl());
                item.put("url", movieList.getHref());

                items.add(item);
            }

            handler.sendMessage(new Message());
            UIHelper.dismiss();
        });
    }

    private void newInit() {
        items = new ArrayList<>();
        this.gridView = this.findViewById(R.id.item_grid);
        if (gridView == null) {
            throw new IllegalArgumentException("the gridView is null");
        }

        currentPage = 1;
        searchStr = "";
        if (mUrl != null) {
            searchStr = mUrl.getText().toString();
        }
        hasNext = true;
        loadSpareItems(currentPage, true);
        this.gridAdapter = new SimpleAdapter(this, items,
                R.layout.function_block, new String[]{"title", "icon"},
                new int[]{R.id.Item_text, R.id.Item_bt});
        gridAdapter.setViewBinder((view, data, textRepresentation) -> {
            //判断是否为我们要处理的对象
            if (view instanceof ImageView && data instanceof String) {
                ImageView iv = (ImageView) view;
                Glide.with(mContext).load(data).error(R.drawable.no_pic).into(iv);
                return true;
            } else {
                return false;
            }
        });
        this.gridView.setAdapter(gridAdapter);
        this.gridAdapter.notifyDataSetChanged();
        this.gridView.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                if (selectedView != null) {
                    selectedView.setBackgroundColor(Color.WHITE);
                }
//                View first = gridView.getChildAt(0);
//                if (first != null) {
//                    first.setBackgroundColor(Color.GRAY);
//                    selectedView = first;
//                }
            } else {
                if (selectedView != null) {
                    selectedView.setBackgroundColor(Color.WHITE);
                    selectedView = null;
                }
            }
        });

        this.gridView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (selectedView != null) {
                    selectedView.setBackgroundColor(Color.WHITE);
                }
                if (view != null) {
                    view.setBackgroundColor(Color.GRAY);
                    selectedView = view;
                }
                //分页功能
                if (position > items.size() - 4 && hasNext) {
                    loadSpareItems(currentPage, false);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                if (selectedView != null) {
                    selectedView.setBackgroundColor(Color.WHITE);
                    selectedView = null;
                }
            }

        });

        this.gridView.setOnItemClickListener((gridView, view, position, id) -> {
            Intent intent1 = new Intent(Bde4Activity.this,
                    Bde4SeasonActivity.class);
            intent1.setData(Uri.parse(JSONObject.toJSONString(new MovieList(items.get(position).get("title").toString(),
                    items.get(position).get("url").toString(),
                    items.get(position).get("icon").toString()))));
            Bde4Activity.this.startActivity(intent1);
        });

        //长按收藏
        this.gridView.setOnItemLongClickListener((parent, view, position, id) -> {
            items.get(position);
            long n = sqLiteHelper.insertFavorite(items.get(position).get("title").toString(),
                    items.get(position).get("icon").toString(),
                    items.get(position).get("url").toString(),
                    PlayerType.BDE4.getCode());
            if (n > 0) {
                Toast.makeText(mContext, "已添加到收藏夹", Toast.LENGTH_SHORT).show();
            } else {
                sqLiteHelper.deleteFavoriteByUrl(items.get(position).get("url").toString());
                Toast.makeText(mContext, "已从收藏夹移除", Toast.LENGTH_SHORT).show();
            }
            return true;
        });

    }

    private void initBtnListener() {
        mUrl = findViewById(R.id.editUrl1);
        mUrl.setInputType(EditorInfo.TYPE_NULL);

        mUrl.setOnClickListener(v -> {
            mUrl.setInputType(InputType.TYPE_CLASS_TEXT);
            mUrl.requestFocus();
            InputMethodManager imm = (InputMethodManager) mUrl
                    .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(mUrl, 0);
        });

        mUrl.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                mUrl.setInputType(InputType.TYPE_NULL);
            }
        });

        mUrl.addTextChangedListener(new TextWatcher() {

            @Override
            public void afterTextChanged(Editable s) {
                if (mUrl.getText() != null) {
                    searchStr = mUrl.getText().toString();
                    currentPage = 1;
                    loadSpareItems(currentPage, true);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {

            }

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {

            }
        });
    }
}
